import { 
  getScoreListRequest, 
  getRawScoreListRequest 
} from '../../api/main';

const scoreCacheKey = "scores"
const rawScoreCacheKey = "rawScores"

Page({ 
  data: {
    type: 1, // 1为有效成绩，2是原始成绩
    list:[],
    termIndex: 0, // 当前学期索引
  }, 
  onLoad(options) {
    this.getList()
  }, 
  getList(){
    // 允许开发者使用 wx.getStorageSync() 函数从本地存储中获取数据
    const cache = wx.getStorageSync(this.data.type == 1 ? scoreCacheKey : rawScoreCacheKey)
    if (cache) {
      this.setData({
        list: cache
      })
      return
    }
    this.update()
  },

  // 区分原始和有效成绩
  update(){
    const that =  this
    let p = null
    if(that.data.type == 1){
      p = getScoreListRequest()
    }else{
      p = getRawScoreListRequest()
    }

    p.then(res => {
      that.setData({
        list: res.data
      })
      wx.setStorageSync(that.data.type == 1 ? scoreCacheKey : rawScoreCacheKey, res.data)
    })
  },

  // 切换成绩类型
  changeScoreType(e){
    // data-type自定义属性，将数据从HTML元素传递到组件,然后在组件中通过event.currentTarget.dataset.type 访问
    const type = e.currentTarget.dataset.type
    this.setData({
      type
    })
    this.getList()
  },

  changeTerm(e){
    // picker组件的bind:change事件特意设计为通过e.detail.value来传递用户选择的索引值
    const termIndex = e.detail.value
    this.setData({
      termIndex
    })
  },
})